import storage from '@/utils/storage'
import request from '@/utils/request'
const REGION_TREE = 'region_tree'
const allRegionKey = 'allRegion'

/**
 * 商品分类 model类
 * RegionModel
 */
export default {
  // 获取所有地区(树状)
  getRegionList (all=false) {
    return new Promise((resolve, reject) => {
      // 判断缓存中是否存在
      const data = storage.get(all?allRegionKey:REGION_TREE)
      // 从服务端获取全部地区数据
      if (data) {
        resolve(data)
      } else {
		  request.get('wx/region/list').then(r=>{
              const allRegion = r.data;
              const tree = this.getTreeData(r.data);
              storage.set(REGION_TREE, tree);
              storage.set(allRegionKey, allRegion);
              resolve(all?allRegion:tree)
		  })
      }
    })
  },
  /**
   * list:[
   * {id: 11, pid: 0, name: "浙江省", type: 1, code: 33},{id: 119, pid: 11, name: "杭州市", type: 2, code: 3301},{id: 1201, pid: 119, name: "江干区", type: 3, code: 330104}]
   * list转换成树状结构
   * */
  getTreeData(list){
        list = list || []
        let tree = []
        let temp = {}
        for(let i in list){
            temp[list[i].id] = list[i]
        }
        for(let i in temp){
            if(temp[i].pid){
                if(!temp[temp[i].pid].children){
                    temp[temp[i].pid].children = new Array()
                }
                temp[temp[i].pid].children.push(temp[i])
            }else{
                tree.push(temp[i])
            }
        }
        return tree
  },

  // 获取所有地区的总数
  getCitysCount () {
    return new Promise((resolve, reject) => {
      // 获取所有地区(树状)
      this.getTreeData().then(data => {
        const cityIds = []
        // 遍历省份
        for (const pidx in data) {
          const province = data[pidx]
          // 遍历城市
          for (const cidx in province.city) {
            const cityItem = province.city[cidx]
            cityIds.push(cityItem.id)
          }
        }
        resolve(cityIds.length)
      })
    })
  }

}
